#include "thread.h"
#include<sys/sendfile.h>
int recvn1(int sockfd, void *buf, int length,int fd){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        ERROR_CHECK(sret,-1,"recv");
        write(fd,p+total,sret);
        total += sret;
    }
    return 0;
}
int updatafile(int sockfd,dirID_t* dir){
    train_t newFile;
    bzero(newFile.buf,sizeof(newFile.buf));
    recvn(sockfd,&newFile.length,sizeof(newFile.length));
    recvn(sockfd,newFile.buf,newFile.length);
    char filename[4096]={0};
    char path[4096];
    bzero(path,4096);
    char userdir[4096];
    bzero(userdir,4096);
    get_user_dir(userdir,dir);
    memcpy(filename,newFile.buf,newFile.length);
    sprintf(path,"%s/%s",userdir,filename);
    int fd=open(path,O_RDWR|O_CREAT|O_TRUNC,0664);
    off_t filesize;
    recvn(sockfd,&newFile.length,sizeof(newFile.length));
    recvn(sockfd,newFile.buf,newFile.length);
    memcpy(&filesize,newFile.buf,sizeof(filesize));
    ftruncate(fd,filesize);
    char *p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    recvn1(sockfd,p,filesize,fd);
    munmap(p,filesize);
    return 0;
}
